; (function (window, $) {
  // dict need
  var dict = {
    professionalText: function (str) {
      console.log(str)
      var arr = str.split(',')
      var dict = ['自由职业者', '个体户', '企业主', '上班族']
      var resArr = []
      for (var i = 0; i < arr.length; i++) {
        resArr.push(dict[arr[i]])
      }
      return resArr.join(',')
    },
    paymentText: function (str) {
      var arr = str.split(',')
      var dict = ['等额本金', '等额本息', '先息后本', '一次性还本付息']
      var resArr = []
      for (var i = 0; i < arr.length; i++) {
        resArr.push(dict[arr[i]])
      }
      return resArr.join('<br/>')
    },
    payment: ['等额本金', '等额本息', '先息后本', '一次性还本付息'],
    loanType: ['信用', '车押', '房押'],
    feature: [
      '无需担保',
      '放款速度快',
      '手续简便',
      '利率低',
      '手续费低',
      '额度高'
    ],
    takeTimes: [
      '一天以内',
      '三天以内',
      '五天以内',
      '一周以内',
      '半月以内',
      '一月以内',
      '三月以内'
    ],
    professional: ['自由职业者', '个体户', '企业主', '上班族'],
    mortgage: ['信用', '车押', '房押', '质押']
  }
  var formobj = {}
  var page1 = paging()

  $(function () {
    //select2 dialog

    //select2
    $('#shrq').select2({
      placeholder: '适合人群',
      language: 'zh-CN'
    })

    $('#cpbq').select2({
      placeholder: '产品特点',
      language: 'zh-CN'
    })

    $('#hkfs').select2({
      placeholder: '还款方式',
      language: 'zh-CN'
    })

    $('#jgmc').select2({
      placeholder: '机构名称',
      language: 'zh-CN',
      tags: 'true'
    })

    $('#jgmc').on('change', function () {
      $(".uploadbtn input[name='logo']").val(
        $(this)
          .find('option:checked')
          .data('logo')
      )
    })

    $('input[type="file"]').on('click', function () {
      if (parseInt($("select[name='instType']").val()) === 0) {
        event.stopPropagation()
        layer.alert('抱歉，暂不能自定义银行产品logo', {
          skin: 'demo-class',
          closeBtn: 0
        })
        //   alert("抱歉，暂不能自定义银行产品logo");
        return false
      }
    })

    //uploadbtn
    $('input[type="file"]').on('change', function () {
      var fileInput = $(this)

      util.fileUpload(fileInput[0].files[0], function (res) {
        fileInput.prev('span').text('点击重新上传')
        fileInput.next('input[type="hidden"]').val(res.data)
      })
    })

    $('.uploadbtn').hover(
      function () {
        var imgUrl = $(this)
          .find("input[type='hidden']")
          .val()
        if (imgUrl !== '') {
          $(this)
            .find('img')
            .attr('src', imgUrl)
          $(this)
            .find('a')
            .attr('href', imgUrl)
            .show()
        }
      },
      function () {
        $(this)
          .find('a')
          .hide()
      }
    )

    //number
    $('input.number').on('keyup', function () {
      var val = $(this).val()
      var exp = new RegExp(/^[0-9]{0,}\.?[0-9]{0,4}$/g)
      if (val.match(exp) === null) {
        $(this).val($(this).data('old'))
      } else {
        $(this).data('old', val)
        if (val.substr(0, 1) == '.') {
          $(this).val('0' + val)
        }
      }
    })

    //int
    $('input.int').on('keyup', function () {
      var val = $(this).val()
      $(this).val(val.replace(/[^0-9]/g, ''))
    })

    //inst
    $("select[name='instType']").on('change', function () {
      getInst($(this).val())
    })

    //dialog
    $('#edit-dialog .cancel-product-btn').on('click', function () {
      $('#edit-dialog').hide()
    })

    $('#del-dialog .cancel-product-btn').on('click', function () {
      $('#del-dialog').hide()
    })

    $('#edit-dialog .edit-product-btn').on('click', saveProduct)

    $('#query-btn').on('click', queryList)

    //paging
    page1.init(1, 0, $('#page1'), function () {
      $("input[name='page']").val($(this).data('page'))
      queryList()
    })
    queryList()
  })

  function queryList() {
    var queryObj = {}

    queryObj.productName = $("input[name='productName']").val()
    queryObj.limit = 6
    queryObj.page = $("input[name='page']").val()

    $('select.query').each(function () {
      if ($(this).val() === '-1') {
        queryObj[$(this).attr('name')] = ''
      } else {
        queryObj[$(this).attr('name')] = $(this).val()
      }
    })

    util.ajax({
      url: '/manager/product/list' + util.obj2query(queryObj),
      type: 'POST',
      success: function (res) {
        renderTable(res.data.rows)
        console.log(res.data.rows)
        page1.init($("input[name='page']").val(), res.data.total)
      }
    })
  }

  function renderTable(arr) {
    var arr_length = arr.length
    var tds = ''
    for (var i = 0; i < arr_length; i++) {
      var item = arr[i]
      var code =
        '<tr><td>' +
        item.name +
        '</td><td>' +
        item.instName +
        '</td><td>' +
        dict.loanType[item.loanType] +
        '</td><td>' +
        dict.professionalText(item.professional || '') +
        '</td><td>' +
        item.loanMin +
        '-' +
        item.loanMax +
        '</td><td>' +
        item.rateMin +
        '%-' +
        item.rateMax +
        '%</td><td>' +
        item.loanTimeMin +
        '-' +
        item.loanTimeMax +
        "月</td><td style='line-height:25px;'>" +
        dict.paymentText(item.payment || '') +
        '</td><td>' +
        item.createTime.split(' ')[0] +
        '</td><td>' +
        item.updateTime.split(' ')[0] +
        '</td>'

      switch (item.auditStatus) {
        case 0:
          code = code + '<td>产品审核中...</td></tr>'
          break
        case 1:
          code =
            code +
            '<td><div class="btnbox"><div class="con ' +
            (item.status == 1 ? 'off' : 'on') +
            '" data-id="' +
            item.id +
            '" data-status="' +
            item.status +
            '"><span class="dot"></span></div></div><div class="btnbox"><div class="edit" data-id="' +
            item.id +
            '">编辑</div></div><div class="btnbox"><div class="del" data-id="' +
            item.id +
            '" data-name="' +
            item.name +
            '">删除</div></div></td></tr>'
          break
        case 2:
          code =
            code +
            '<td><div class="btnbox" style="color:#FF0000" title="' +
            item.auditRemark +
            '">审核失败</div><div class="btnbox"><div class="edit" data-id="' +
            item.id +
            '">编辑</div></div><div class="btnbox"><div class="del" data-id="' +
            item.id +
            '" data-name="' +
            item.name +
            '">删除</div></div></td></tr>'
          break
        default:
          break
      }

      // console.log(code)
      tds += code
    }
    $('table.channel-good-table tbody').html(tds)
    bindAction()
  }

  function bindAction() {
    // toggleStatus
    $('.con').on('click', function () {
      var dom = $(this)
      var id = dom.data('id')
      var toStatus = dom.data('status') == 0 ? 1 : 0

      util.ajax({
        url: '/manager/product/modifyStatus/' + id,
        data: {
          status: toStatus
        },
        success: function (res) {
          console.log(res)
          dom.data('status', toStatus)
          if (toStatus == 1) {
            dom.removeClass('on').addClass('off')
          } else {
            dom.removeClass('off').addClass('on')
          }
        },
        error: function (err) {
          if (err.status === 500) {
            layer.alert(JSON.parse(err.responseText).msg, {
              skin: 'demo-class',
              closeBtn: 0
            })
            // alert(JSON.parse(err.responseText).msg)
          }
        }
      })
    })

    // delete
    $('.del').on('click', function () {
      var dom = $(this)
      var id = dom.data('id')
      var name = dom.data('name')

      $('#del-name').text(name)
      $('#del-dialog .del-product-btn').data('id', id)

      $('#del-dialog').show()
    })

    $('#del-dialog .del-product-btn').on('click', function () {
      var dom = $(this)
      util.ajax({
        url: '/manager/product/delete/' + dom.data('id'),
        type: 'GET',
        success: function (res) {
          $('#del-dialog').hide()
          queryList()
        }
      })
    })

    // edit
    $('.edit').on('click', function () {
      var dom = $(this)
      var id = dom.data('id')

      util.ajax({
        url: '/manager/product/' + id,
        type: 'GET',
        success: function (res) {
          formobj = res.data.detail
          formobj.serviceFee = res.data.serviceFee
          editDialog()
        }
      })
    })
  }

  // show edit dialog

  function editDialog() {
    $('#edit-dialog').show()

    $('input[type="text"].formobj,textarea.formobj').each(function () {
      var key = $(this).attr('name')
      $(this).val(formobj[key])
    })

    // select one by one
    $("select[name='loanType'].formobj").val(formobj.loanType)

    $("select[name='instType'].formobj")
      .val(formobj.instType)
      .trigger('change')
    $("select[name='payment'].formobj").val(formobj.payment)
    $("select[name='carType'].formobj").val(formobj.carType)
    $("select[name='houseType'].formobj").val(formobj.houseType)
    $("select[name='takeTimes'].formobj").val(formobj.takeTimes)

    // select2 one by one
    $("select[name='features'].formobj")
      .val(formobj.features.split(','))
      .trigger('change')
    $("select[name='professional'].formobj")
      .val(formobj.professional.split(','))
      .trigger('change')

    $("select[name='payment'].formobj")
      .val(formobj.payment.split(','))
      .trigger('change')

    //hidden
    $("input[name='logo']").val(formobj.logo)
  }

  function saveProduct() {
    var vali = true

    // get all text
    $('input[type="text"].formobj').each(function () {
      if (!vali) {
        return
      }

      if ($(this).val() === '') {
        layer.alert($(this).data('label') + ' 未填写', {
          skin: 'demo-class',
          closeBtn: 0
        })
        // alert($(this).data('label') + ' 未填写')
        vali = false
      }
      var key = $(this).attr('name')
      var val = $(this).val()
      formobj[key] = val
    })

    // get all select
    $('select.formobj').each(function () {
      if (!vali || $(this).attr('name') == 'instId') {
        return
      }
      if ($(this).val() === -1 || $(this).val() === null) {
        console.log('-1 or null', $(this).attr('name'))
        vali = false
      }
      var key = $(this).attr('name')
      var val = $(this).val()
      formobj[key] = val
    })

    //get all hidden
    $('input[type="hidden"].formobj').each(function () {
      if (!vali) {
        return
      }
      if ($(this).val === '') {
        vali = false
      }
      var key = $(this).attr('name')
      var val = $(this).val()
      formobj[key] = val
    })

    // get all textarea
    $('textarea.formobj').each(function () {
      if (!vali) {
        return
      }
      if ($(this).val === '') {
        vali = false
      }
      var key = $(this).attr('name')
      var val = $(this).val()
      formobj[key] = val
    })

    if (!vali) {
      return
    }

    // text
    formobj.featuresText = []
    formobj.paymentText = []
    formobj.professionalText = []

    for (var i = 0; i < formobj.features.length; i++) {
      formobj.featuresText.push(dict.feature[formobj.features[i]])
    }

    for (var j = 0; j < formobj.payment.length; j++) {
      formobj.paymentText.push(dict.payment[formobj.payment[j]])
    }

    for (var j = 0; j < formobj.professional.length; j++) {
      formobj.professionalText.push(dict.professional[formobj.professional[j]])
    }

    // let's check instid
    // if isNaN === true ,it will be a string
    if (isNaN($("select[name='instId']").val())) {
      if (parseInt(formobj.instType) === 0) {
        layer.alert('暂不能自定义银行机构', {
          skin: 'demo-class',
          closeBtn: 0
        })
        // alert('暂不能自定义银行机构')
        return
      } else {
        formobj.instName = $("select[name='instId']").val()
      }
    } else {
      formobj.instId = $("select[name='instId']").val()
      formobj.instName = $("select[name='instId'] option:checked").text()
    }

    //convert array to string

    for (var gg in formobj) {
      if (formobj[gg] instanceof Array) {
        console.log()
        formobj[gg] = formobj[gg].join(',')
      }
    }

    //big small
    if (
      parseInt($("input[name='rateMax']").val()) <
      parseInt($("input[name='rateMin']").val())
    ) {
      layer.alert('最小贷款利率不能大于最大贷款利率', {
        skin: 'demo-class',
        closeBtn: 0
      })
      return
    }

    if (
      parseInt($("input[name='loanTimeMax']").val()) <
      parseInt($("input[name='loanTimeMin']").val())
    ) {
      layer.alert('最小贷款期限不能大于最大贷款期限', {
        skin: 'demo-class',
        closeBtn: 0
      })
      return
    }

    if (
      parseInt($("input[name='loanMax']").val()) <
      parseInt($("input[name='loanMin']").val())
    ) {
      layer.alert('最小贷款额度不能大于最大贷款额度', {
        skin: 'demo-class',
        closeBtn: 0
      })
      return
    }

    //faker data
    // formobj.productId=0;
    formobj.credit = 0
    formobj.remark = 'afosudfh'

    var id = formobj.id
    delete formobj.id
    delete formobj.createTime
    delete formobj.updateTime
    delete formobj.updateUser
    delete formobj.updateName

    console.log('before send', formobj)

    util.ajax({
      url: '/manager/product/modify/' + id,
      type: 'POST',
      data: formobj,
      success: function (res) {
        $('#edit-dialog').hide()
        queryList()
      }
    })

    // we can async back formobj.id
    formobj.id = id
  }

  function getInst(id) {
    $.ajax({
      url: util.host + '/common/institution/getInstitutionList?type=' + id + '&limit=100',
      type: 'POST',
      success: function (res) {
        var arr = res.data.rows
        var arr_length = arr.length
        var html = ''
        for (var i = 0; i < arr_length; i++) {
          html +=
            '<option value="' +
            arr[i].id +
            '" data-logo="' +
            arr[i].logo +
            '">' +
            arr[i].name +
            '</option>'
        }

        $('select[name="instId"]').html(html)

        // edit formobj hook
        if (formobj.instId) {
          $("select[name='instId'].formobj")
            .val(formobj.instId)
            .trigger('change')
        } else {
          $("select[name='instId'].formobj").append(
            '<option value="' +
            formobj.instName +
            '" data-logo="' +
            formobj.logo +
            '">' +
            formobj.instName +
            '</option>'
          )
          $("select[name='instId'].formobj")
            .val(formobj.instName)
            .trigger('change')
        }
      }
    })
  }
})(window, jQuery)
